<?php

namespace App\Http\Controllers;

use App\Models\Admin;
use App\Models\Cities;
use App\Models\FilmTypeMaster;
use App\Models\MacroManagement;
use App\Models\MakeMaster;
use App\Models\ModelMaster;
use App\Models\PartMaster;
use App\Models\PhoneExtension;
use App\Models\ProductTypes;
use App\Models\ProvinceMaster;
use App\Models\RegionMaster;
use App\Models\Warranty;
use Encore\Admin\Grid\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Log;

class IndexController extends Controller
{
    public function asp(Request $request)
    {
        $t = $request->input('t');
        $value = trim(request()->input('svalue'));
        $value = str_replace(' ','', $value);
        $data = [];
        $coverages = [];
        $type = '';
        $model = '';
        $datas = [];

        $warranty_id = $request->input('warranty_id');
        if (!empty($warranty_id)) {
            $model = Warranty::where('warranty_id', $warranty_id)->where('approved', 1)->first();
            if (empty($model->id)){
                $model = '';
            }
        }
        if (!empty($value) && empty($model)) {
            $columns = ['w.warranty_id', 'w.phone_number', 'w.license_plate', 'w.vin_number', 'p.precut_id'];

            $precutData = DB::table('warranty as w')
                ->leftJoin('new_precut as p', 'p.id', 'w.precut_id')
                ->whereNull('w.deleted_at')
                ->whereNull('p.deleted_at')
                ->where(function ($query) use ($value, $columns) {
                    foreach ($columns as $k => $c) {
                        if ($c === 'w.vin_number' && strlen($value) < 17) {
                            $query->orWhere($c, 'like', "%{$value}%");
                        } else {
                            $query->orWhere($c, $value);
                        }
                    }
                })
                ->where('p.id', '>', 0)
                ->where('w.approved', 1)
                ->select(['w.*', 'p.precut_id', DB::raw('p.id as pid')])
                ->get();

            $rollData = DB::table('warranty as w')
                ->leftJoin('warranty_to_vehicle_coverage as p', 'p.warranty_id', 'w.id')
                ->whereNull('w.deleted_at')
                ->whereNull('p.deleted_at')
                ->where(function ($query) use ($value, $columns) {
                    foreach ($columns as $k => $c) {
                        if ($c === 'p.precut_id') {
                            continue;
                        }
                        if ($c === 'w.vin_number' && strlen($value) < 17) {
                            $query->orWhere($c, 'like', "%{$value}%");
                        } else {
                            $query->orWhere($c, $value);
                        }
                    }
                })
                ->whereIn('p.film_type_id', function ($query) {
                    $query->select('id')
                        ->from('film_type_master')
                        ->where('english_value', 'like', 'ASP-%');
                })
                ->where('w.approved', 1)
                ->select(['w.*', 'p.roll_number', DB::raw('p.id as pid')])
                ->get();
            if ($precutData->isNotEmpty()) {
                foreach ($precutData as $item) {
                    $datas[] = $item;
                }
            }

            if ($rollData->isNotEmpty()) {
                foreach ($rollData as $item) {
                    $datas[] = $item;
                }
            }
        }
        return view('asp-warranty', [
            'datas' => $datas,
            'model' => $model,
        ]);
    }

    public function index(Request $request)
    {
        $t = $request->input('t');
        $value = trim(request()->input('svalue'));
        $data = [];
        $coverages = [];
        $warranty_id = $request->input('warranty_id');
        //$wids = session('warranty_ids');
        // $wids = [2008021968=>1, 2009093280=>1, 10108089=>1];
        $type = '';
        $model = '';
        $rollnumber = '';


        if (!empty($warranty_id)) {
            $model = Warranty::where('warranty_id', $warranty_id)->where('approved', 1)->first();

            if (!empty($model->warranty_to_vehicle_coverage)) {
                $data = [];
                foreach ($model->warranty_to_vehicle_coverage as $coverage) {
                    $length = 0;
                    if (in_array($coverage->part_id, [18, 150, 152, 153])) {
                        if ($length < $coverage->length) {
                            $result = $coverage;
                        }
                    }
                }
                if (!empty($result)) {
                    $data[] = $result;
                }

                foreach ($model->warranty_to_vehicle_coverage as $key => $coverage) {
                    $data[] = $coverage;
                }

                $model->warranty_to_vehicle_coverage = $data;
            }
            if (!empty($model->warranty_id) && !empty($model->first_name)) {
                $type = 'showWarrantyDetails';
                $coverages = $model->coverages();
                $images = $model->images();
                //Log::info($warranty_id.'coverages', $coverages->toArray());

                $upd = [];
                foreach ($coverages as $k => $v) {
                    if ($v['product_type_id'] == 1) {
                        $upd[$v->roll_number] = @$upd[$v->roll_number] + $v->length;
                    }
                }
                arsort($upd);
                $rollnumber = 0;
                foreach ($upd as $k => $v) {
                    $rollnumber = $rollnumber ?: $k;
                }

                if (!empty($coverages)) {
                    $data = [];
                    foreach ($coverages as $coverage) {
                        if ($coverage->product_type_id == 1) {
                            if ($coverage->roll_number == $rollnumber) {
                                $data[$rollnumber][] = $coverage;
                            }
                        } else {
                            $data[$coverage->roll_number][] = $coverage;
                        }
                    }
                    $coverages = $data;
                }
            }
        }

        if (empty($model) && $t === 'warranty' && !empty($value) && strlen($value) >  4) {
            $columns = ['w.warranty_id', 'w.phone_number', 'w.license_plate', 'w.vin_number'];
            $data = DB::table('warranty as w')
                ->where(function ($query) use ($value, $columns) {
                    foreach ($columns as $k => $c) {
//                        if ($c === 'w.vin_number' && strlen($value) < 17) {
//                            $query->orWhere($c, 'like', "%{$value}%");
//                        } else {
//                            $query->orWhere($c, $value);
//                        }
                        $query->orWhere($c, $value);
                    }
                })
                ->whereNull('w.deleted_at')
                // ->leftJoin('users as u', 'u.id', 'w.user_id')
                ->where('w.warranty_id', '>=', 1)
                ->where('w.approved', 1)
                ->where('w.first_name', '!=', '0')
                ->whereNotNull('w.first_name')
                ->whereNotNull('w.license_plate')
                ->whereIn('w.id', function ($query) {
                    $query->select('warranty_id')
                        ->from('warranty_to_vehicle_coverage')
                        ->whereIn('film_type_id', function ($query) {
                            $query->select('id')
                                ->from('film_type_master')
                                ->where('english_value', 'not like', 'ASP-%');
                        });
                })
                /*->where(function ($query) {
                    $query->where('w.first_name', '!=', 0)
                        ->whereNotNull('w.first_name');
                })*/
                ->limit(80)
                ->orderByDesc('w.id')
                ->select(['w.id', 'w.user_id', 'w.phone_number', 'w.warranty_id', 'w.license_plate', 'w.first_name', 'w.make_id', 'w.model_id', 'w.year_id', 'w.installation_date', 'w.approved_date',  'w.city', 'w.dealer_name'])
                ->get();

            $ids = Arr::pluck($data, 'id');

            $wvc = DB::table('warranty_to_vehicle_coverage as wvc')
                ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
                ->whereIn('wvc.warranty_id', $ids)
                ->leftJoin('roll_master as rm', 'rm.roll_number', 'wvc.roll_number')
                ->select(['wvc.warranty_id', 'wvc.roll_number', 'wvc.length', 'rm.film_type_id', 'rm.product_type_id', 'wvc.part_id', 'wvc.precut_or_manual','wvc.start_time','wvc.end_time'])
                ->whereNull('wvc.deleted_at')
                ->orderByDesc('wvc.id')
                ->get();
            $upd = [];
            foreach ($wvc as $k => $v) {
                $upd[$v->roll_number] = @$upd[$v->roll_number] + $v->length;
            }

            arsort($upd);
            foreach ($upd as $k => $v) {
                $rollnumber = $rollnumber ?: $k;
            }

            foreach ($wvc as $k => $v) {
                if (empty($coverages[$v->warranty_id])) {
                    $coverages[$v->warranty_id] = [];
                }
                $coverages[$v->warranty_id][] = $v;
            }


            if (!empty($coverages)) {
                $setCoverageData = [];
                $result = [];
                foreach ($coverages as $key => $coverage) {
                    $length = 0;
                    foreach ($coverage as $item) {
                        if (in_array($item->part_id, [18, 150, 152, 153])) {
                            if ($length < $item->length) {
                                $result[$key] = $item;
                            }
                        }
                    }
                }
                foreach ($result as $key => $item) {
                    $setCoverageData[$key][] = $item;
                }
                foreach ($coverages as $key => $coverage) {
                    foreach ($coverage as $item) {
                        if (!in_array($item->part_id, [18, 150, 152, 153])) {
                            $setCoverageData[$key][] = $item;
                        }
                    }
                }

                $coverages = $setCoverageData;
            }

            foreach ($data as &$item) {
                $item->roll_number = !empty($coverages[$item->id]) ?  ($coverages[$item->id][0]->roll_number ?? $rollnumber) : $rollnumber;
            }
        }

        return view('welcome', [
            'datas'=>$data,
            'coverages'=>$coverages,
            'type' => $type,
            'model' => $model ?? [],
            'rollnumber' => $rollnumber ?? '',
            'images'     => $images ?? [],
        ]);
    }

    public function getPhone(Request $request)
    {
       $searchValue = $request->get('search_value');
       if (empty($searchValue) || strlen($searchValue) <= 4) {
           return fs403('数据有误');
       }

        $columns = ['w.warranty_id', 'w.license_plate', 'w.phone_number','w.vin_number'];
        $data = DB::table('warranty as w')
            ->where(function ($query) use ($searchValue, $columns) {
                foreach ($columns as $k => $c) {
                    $query->orWhere($c, $searchValue);
                }
            })
            ->whereNull('w.deleted_at')
            // ->leftJoin('users as u', 'u.id', 'w.user_id')
            ->where('w.warranty_id', '>=', 1)
            ->where('w.approved', 1)
            ->where('w.first_name', '!=', '0')
            ->whereNotNull('w.first_name')
            ->whereNotNull('w.license_plate')
            ->orderByDesc('w.id')
            ->select(['w.phone_number'])
            ->first();

        if (empty($data) || empty($data->phone_number)) {
            return fs404('数据没有找到');
        }

        return ['status'=>'SUCCESS', 'phone_number'=> substr(trim($data->phone_number), -4)];
    }

    public function lang_change(Request $request)
    {
        $language = (int) $request->input('lang');
        if ($language == 1) {
            App::setLocale('en');
            session(['language'=>1]);
        } elseif ($language == 2) {
            App::setLocale('zh_tw');
            session(['language'=>2]);
        } elseif ($language == 3) {
            App::setLocale('zh');
            session(['language'=>3]);
        } else {
            App::setLocale('zh');
            session(['language'=>3]);
        }
        return ['status'=>'SUCCESS'];
    }

    public function warranty(Request $request)
    {
        $value = trim(request()->input('svalue'));
        $columns = ['warranty_id', 'phone_number', 'license_plate'];
        if (empty($value)) {
            return ['status'=>false, 'data'=>$this->mH1()];
        }
        $warranty = new Warranty();
        $warranty = $warranty->where(function ($query) use ($value, $columns) {
            foreach ($columns as $k => $c) {
                $query->orWhere($c, $value);
            }
        });
        $data = $warranty->get();
        if (!count($data)) {
            return ['status'=>false, 'data'=>$this->mH1()];
        }
        $res = [];
        foreach ($data as $k => $v) {
            $res[] = $this->mH3($v);
        }
        return ['status'=>'SUCCESS', 'data'=>$res];
        return $warranty;

    }

    protected function mH3($warranty)
    {
        $res = [
            [
                'value' => ts('VALIDWARRANTYID'),
            ],
            [
                'label' => ts('WARRANTYID'),
                'value' => $warranty->warranty_id,
            ],
            [
                'label' => ts('CUSTOMERNAME'),
                'value' => $warranty->first_name,
            ],
            [
                'label' => ts('MAKE'),
                'value' => ts('make_maser.'.$warranty->make_id),
            ],
            [
                'label' => ts('MODEL'),
                'value' => $warranty->model_id,
            ],
            [
                'label' => ts('YEAR'),
                'value' => $warranty->year_id,
            ],
            [
                'label' => ts('INSTALLATIONDATE'),
                'value' => $warranty->installation_date,
            ],
            [
                'label' => ts('COMPANYNAME'),
                'value' => $warranty->company_name,
            ],
            [
                'label' => ts('CITY'),
                'value' => ts('cities.'.$warranty->make_id),
            ]
        ];
        return $res;
    }

    protected function mH2($warranty)
    {
        $item = '<table class="table table-bordered">';
        $item .= '<tbody>';
        $item .= '<tr><td colspan="2">'.ts('VALIDWARRANTYID').'</td></tr>';
        $item .= '</tbody>';
        $item .= '</table>';
        return $item;
    }

    protected function mH1()
    {
        $msg = '';
        $msg .= "<p>".ts('WERRORLINE1')."</p>";

        return $msg;

    }

}
